function [digits] = extractDigits(fileName,n)
%Given a MNIST image file, extracts the first n images.
%The images are returned as a 28x28xn matrix.


%Open file for reading in big-endian format
dataFile = fopen(fileName,'r','b');
assert(dataFile ~= -1,'Problem opening MNIST image file');

%Check magic number
magic=fread(dataFile,1,'int32');
assert(magic == 2051,'Invalid magic number, not a MNIST image file')

numImages=fread(dataFile,1,'int32');
n=min(n,numImages);

height=fread(dataFile,1,'int32');
width=fread(dataFile,1,'int32');


digits=zeros(height,width,n);

for i=1:n
    digits(:,:,i)=(fread(dataFile,[width height],'uchar'))';
end

fclose(dataFile);

end

